import json
import datetime
from django.http import JsonResponse
from utils.views import LoginRequiredJSONMixin
# Create your views here.
from django.views import View
from apps.order.models import Order
from apps.homes.models import House
from ihome import settings
class OrderView(LoginRequiredJSONMixin,View):
    '''
    添加订单
    '''

    def post(self, request):
        json_dict = json.loads(request.body.decode())
        start_date = json_dict.get('start_date')
        end_date = json_dict.get('end_date')
        house_id = json_dict.get('house_id')
        try:
            start_date = datetime.datetime.strptime(start_date, '%Y-%m-%d')
            end_date = datetime.datetime.strptime(end_date, '%Y-%m-%d')
            if end_date <= start_date:
                return JsonResponse({'errno': 400,'errmsg': '日期参数有误'})
        except Exception as e:
            return JsonResponse({'errno': 400,'errmsg': '日期参数有误'})

        try:
            house = House.objects.get(id=house_id)
        except Exception as e:
            return JsonResponse({'errno': 400,'errmsg': '没有此房间信息'})
        # 判断入住天数是否符合房间设定最大最小值
        days = (end_date - start_date).days
        if days < house.min_days:
            return JsonResponse({'errno': 400,'errmsg': '入住天数至少为%s天' % house.min_days})
        if house.max_days:
            if days > house.max_days:
                return JsonResponse({'errno': 400,'errmsg': '入住天数至多为%s天' % house.max_days})

        if house.user_id == request.user.id:
            return JsonResponse({'errno': 400,'errmsg': '不能预定自己的房间'})

        if house.order_set.filter(end_date__gt=start_date, begin_date__lt=end_date).count():
            return JsonResponse({'errno': 400,'errmsg': '该时段,此房间已有客人预定'})

        order = Order.objects.create(
            user=request.user,
            house=house,
            begin_date=start_date,
            end_date=end_date,
            days=days,
            house_price=house.price,
            amount=house.price * days)
        return JsonResponse({'errno': 0, 'data': {'order_id': order.id}})


    def get(self, request):
        user = request.user
        # 取当前角色的标识：房客：custom,房东：landlord

        role = request.GET.get('role')
        if role is None:
            return JsonResponse({'errno':400, 'errmsg': "参数错误"})
        # 房客
        if role == 'custom':
            orders = Order.objects.filter(user=user).order_by('-create_time')
        # 房东
        elif role == 'landlord':
            houses = House.objects.filter(user=user)  # 通过房东id获取其房屋名称
            houses_ids = [house.id for house in houses]
            orders = Order.objects.filter(house_id__in=houses_ids).order_by('-create_time')
        orders_dict_li = []
        for order in orders:
            orders_dict_li.append({
                "order_id": order.id,
                "title": order.house.title,
                "img_url": settings.QN_BASE_URL + order.house.index_image_url if order.house.index_image_url else " ",
                "start_date": order.begin_date.strftime("%Y-%m-%d"),
                "end_date": order.end_date.strftime("%Y-%m-%d"),
                "ctime": order.create_time.strftime("%Y-%m-%d %H:%M:%S"),
                "days": order.days,
                "amount": order.amount,
                "status": Order.ORDER_STATUS_ENUM[order.status],
                "comment": order.comment if order.comment else ""
            })
        return JsonResponse({'errno':0, 'errmsg': "OK", 'data': {"orders": orders_dict_li}})


class AcceptView(LoginRequiredJSONMixin,View):
    '''
    接单拒单
    '''
    def put(self, request, order_id):
        data = json.loads(request.body.decode())
        action = data.get('action')  # 操作类型：【accept: 接单，reject：拒单】
        reason = data.get('reason')  # 拒单原因，如果是拒单时需要传入

        try:
            order = Order.objects.get(pk=order_id)
        except Order.DoesNotExist as e:
            return JsonResponse({'errno': 400, 'errmsg': '订单号不存在'})

        # 校验参数
        if not action:
            return JsonResponse({'errno': 400, 'errmsg': '缺少必要参数'})

        if action not in ['accept', 'reject']:
            return JsonResponse({'errno': 400, 'errmsg': '参数错误'})

        # 业务数据处理
        # order_id=self.kwargs.get('order_id')
        if action == 'accept':
            order.status = Order.ORDER_STATUS["WAIT_COMMENT"]
            order.save()

            return JsonResponse({
                'errno': 0,
                'errmsg': '订单已接受'
            })

        if action == 'reject':
            if reason is None:
                return JsonResponse({'errno': 400, 'errmsg': '缺少必要参数'})

            order.status = Order.ORDER_STATUS["REJECTED"]
            order.comment = reason
            order.save()

            return JsonResponse({
                'errno': 0,
                'errmsg': 'OK'
            })
#评价订单
class CommentOrderView(LoginRequiredJSONMixin, View):

    def put(self, request, order_id):
        data = json.loads(request.body.decode())
        comment = data.get('comment')

        if not comment:
            return JsonResponse({'errno': 400, 'errmsg': '评论不能为空'})

        try:
            order = Order.objects.get(pk=order_id)
            order.status = Order.ORDER_STATUS["COMPLETE"]
            order.comment = comment
            order.save()
        except Order.DoesNotExist as e:
            return JsonResponse({'errno': 400, 'errmsg': '订单不存在'})

        return JsonResponse({'errno': '0', 'errmsg': '评论成功'})